//
//  ViewController.m
//  tentecthORC
//
//  Created by 湖南机友科技有限公司 on 2018/3/22.
//  Copyright © 2018年 湖南机友科技有限公司. All rights reserved.
//

#import "ViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "HYBNetworking.h"
#import "AFNetworking.h"
#import "UIImage+Extended.h"
#import "MJExtension.h"
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取当前时间戳
    NSDate *currentTime = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time = [currentTime timeIntervalSince1970];
    NSString *currentStr = [NSString stringWithFormat:@"%.0f",time];
    NSLog(@"当前的时间戳是%@",currentStr);
               
    NSString *randomStr=[self createUuid];

    UIImage *originImage = [UIImage imageNamed:@"1000.png"];
    NSData *data = UIImageJPEGRepresentation(originImage, 1.0f);
    /// base64 编码
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    /// 0.URL 编码
    NSString *unicodeStr = [encodedImageStr  stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];;

    ///1. 获取接口签名的参数
    NSMutableDictionary *mudic = [NSMutableDictionary dictionary];
    [mudic setObject:@"1106471787" forKey:@"app_id"];
    [mudic setObject:currentStr forKey:@"time_stamp"];
    [mudic setObject:randomStr forKey:@"nonce_str"];
    [mudic setObject:unicodeStr forKey:@"image"];
    NSString *signStr =   [self jlGetSignData:mudic withAppKey:@"zvVIWBt07Tl3uQlM"];
    
    
    ///2. 发送网络请求的参数
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionary];
    [requestDic setObject:@"1106471787" forKey:@"app_id"];
    [requestDic setObject:currentStr forKey:@"time_stamp"];
    [requestDic setObject:randomStr forKey:@"nonce_str"];
    [requestDic setObject:encodedImageStr forKey:@"image"];
    [requestDic setObject:signStr forKey:@"sign"];

    
    [self netWorkTest:requestDic];
    
    
    
}

//计算鉴权值
- (NSString*)jlGetSignData:(NSMutableDictionary*)dic withAppKey:(NSString*)appKey
{ 
    
    NSArray *allKeys = [dic allKeys];
    NSArray *sortArr = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        //
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSLog(@"sortArr is %@",sortArr);
    
    NSMutableArray *valueArr = [NSMutableArray array];
    for (NSString *sortString in sortArr) {
        NSString *valueStr = [dic objectForKey:sortString];
        NSString *urlEncode=  (NSString *)CFBridgingRelease(
                                    CFURLCreateStringByAddingPercentEscapes( NULL,
                                    (__bridge CFStringRef)valueStr, NULL,
                                    (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
        [valueArr addObject:urlEncode];
    }
    NSLog(@"valueArr is %@",valueArr);
    NSMutableArray *signArr = [NSMutableArray array];
    for (int i = 0; i < sortArr.count; i ++) {
        NSString *keyValueStr = [NSString stringWithFormat:@"%@=%@",sortArr[i],valueArr[i]];
        [signArr addObject:keyValueStr];
    }
    
    NSString *sign = [signArr componentsJoinedByString:@"&"];
    
    NSLog(@"最终拼接的字符串是%@",sign);
    
    NSMutableString *muStr = [NSMutableString string];
    [muStr appendString:sign];
    [muStr appendString:[NSString stringWithFormat:@"&app_key=%@",appKey]];
    NSLog(@"MD5运算的源数据是%@\n",muStr);
    
   NSString *secStr =  [self md5:muStr];
   NSString *upperSec = [secStr uppercaseString];
    
    NSLog(@"MD5加密的结果是%@",upperSec);
    
   
  
    return upperSec;
    
    
}
-(NSString*)createUuid;
{
    char data[10];
    for (int x=0;x<10;data[x++] = (char)('A' + (arc4random_uniform(26))));
    
    return [[NSString alloc] initWithBytes:data length:10 encoding:NSUTF8StringEncoding];
}
- (NSString *)md5:(NSString *)str
{
   
    const char *cStr = [str UTF8String];
     NSLog(@"md5参数是%s",cStr);
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (void)netWorkTest:(NSMutableDictionary *)mudic
{
    NSLog(@"接口请求参数是%@",mudic);

     


    NSString *jiekoujianding =@"https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr";

    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    [manger POST:jiekoujianding parameters:mudic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"responseObject==%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"error==%@",error);
    }];


    
}

#pragma mark  ====  第二总网络请求 方法
-(void)originNetWork:(NSMutableDictionary *)mudic{
    
    
    ///NSString *testURL = @"https://api.ai.qq.com/fcgi-bin/nlp/nlp_textpolar?";
    NSString *testURL = @"https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr?";
    NSArray *keys = [mudic allKeys];
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i <keys.count; i ++) {
        NSString *key = [keys objectAtIndex:i ];
        NSString *value = [mudic objectForKey:key];
        NSString *com = [[NSString alloc]initWithFormat:@"%@=%@",key,value ];
        [arr addObject:com];
        
    }
    NSString *sign = [arr componentsJoinedByString:@"&"];
    NSMutableString *mustr = [NSMutableString string];
    [mustr appendString:testURL];
    [mustr appendString:sign];
    NSLog(@"完整的请求参数是%@",mustr);
    
    testURL = [mustr  stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:mustr];
    
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方法
    request.HTTPMethod = @"POST";
    
    
    NSURLSession *session  = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask =  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (error) {
            NSLog(@"error is %zd",error.code);
        }else
        {
            NSLog(@"data is %zd",data.length);
            NSLog(@"data is %@",data);
            NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            
            NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            
            NSLog(@"解析得出的dic is %@.... str=%@",dic,str);
        }
    }];
    [dataTask resume];
}
///=====================================  照片选择

-(void)chooseImage{
    
    //调用系统相册的类
    UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
    //设置选取的照片是否可编辑
    pickerController.allowsEditing = YES;
    //设置相册呈现的样式
    UIAlertController *alertCtro=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertCtro addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //调取摄像头
        pickerController.sourceType =  UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:pickerController animated:YES completion:nil];
        
        
    }]];
    
    [alertCtro addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        pickerController.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;//图片分组列表样式
        
        [self presentViewController:pickerController animated:YES completion:nil];
        
        
        
    }]];
    
    [alertCtro addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }]];
    
    pickerController.delegate = self;
    //使用模态呈现相册
    [self presentViewController:alertCtro animated:YES completion:^{}];
    
    
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *resultImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    UIImage *image = [resultImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    

    NSArray *dictArry=@[@{
                            @"MobileCode":@"15111220570",
                            @"Name":@"zengw",
                            @"CommitContent":@"田农八部"
                            }];
    
    NSMutableDictionary *dictM=[NSMutableDictionary dictionary];
    
    dictM[@"Id"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_messageId"];
    dictM[@"Token"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_token"];
    dictM[@"AddMobilePhoneDetails"]= [dictArry mj_JSONString];
    
    /// 上传拍照解析到的数据
   [HYBNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",host_api,AddMobilePhone_api] refreshCache:YES params:dictM success:^(id response) {
        
        NSLog(@"拍照解析到的数据上传成功==== %@",response);
    } fail:^(NSError *error) {
        
        NSLog(@"拍照解析到的数据上传失败==== %@",error);
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
